import { useState, useRef } from "react";
import { Cat, X, Send } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";

// 简单拖拽实现
function useDraggable(initialPosition = { x: 40, y: 40 }) {
  const [position, setPosition] = useState(initialPosition);
  const dragging = useRef(false);
  const offset = useRef({ x: 0, y: 0 });

  const onMouseDown = (e: React.MouseEvent) => {
    dragging.current = true;
    offset.current = {
      x: e.clientX - position.x,
      y: e.clientY - position.y,
    };
    document.addEventListener("mousemove", onMouseMove);
    document.addEventListener("mouseup", onMouseUp);
  };

  const onMouseMove = (e: MouseEvent) => {
    if (!dragging.current) return;
    setPosition({
      x: e.clientX - offset.current.x,
      y: e.clientY - offset.current.y,
    });
  };

  const onMouseUp = () => {
    dragging.current = false;
    document.removeEventListener("mousemove", onMouseMove);
    document.removeEventListener("mouseup", onMouseUp);
  };

  return { position, onMouseDown };
}

export const AIChatAssistant = () => {
  const [isOpen, setIsOpen] = useState(false);
  const [messages, setMessages] = useState<{ role: 'user'|'ai', text: string }[]>([]);
  const [input, setInput] = useState("");
  const { position, onMouseDown } = useDraggable({ x: window.innerWidth - 120, y: window.innerHeight - 180 });

  const handleSend = () => {
    if (!input.trim()) return;
    setMessages([...messages, { role: 'user', text: input }]);
    // 这里可接入AI回复逻辑，先用固定回复
    setTimeout(() => {
      setMessages(msgs => [...msgs, { role: 'ai', text: 'AI助手收到：' + input }]);
    }, 600);
    setInput("");
  };

  return (
    <div style={{ position: 'fixed', left: position.x, top: position.y, zIndex: 9999 }}>
      {isOpen && (
        <div className="mb-2 animate-scale-in">
          <Card className="w-80 shadow-lg border-2 border-blue-200 bg-gradient-to-br from-blue-50 to-purple-50">
            <CardHeader className="flex flex-row items-center justify-between pb-3 cursor-move" onMouseDown={onMouseDown} style={{ cursor: 'move' }}>
              <CardTitle className="text-lg font-semibold text-blue-700 flex items-center gap-2">
                <Cat className="h-5 w-5" />
                AI Assistant
              </CardTitle>
              <Button variant="ghost" size="sm" onClick={() => setIsOpen(false)} className="h-6 w-6 p-0 hover:bg-blue-100">
                <X className="h-4 w-4" />
              </Button>
            </CardHeader>
            <CardContent className="pt-0 flex flex-col gap-2" style={{ maxHeight: 320, overflowY: 'auto' }}>
              {messages.length === 0 && <div className="text-gray-400 text-sm text-center py-8">How can I help you today?</div>}
              {messages.map((msg, idx) => (
                <div key={idx} className={msg.role === 'user' ? 'text-right' : 'text-left'}>
                  <span className={msg.role === 'user' ? 'inline-block bg-blue-100 text-blue-800 rounded-lg px-3 py-1 my-1' : 'inline-block bg-purple-100 text-purple-800 rounded-lg px-3 py-1 my-1'}>
                    {msg.text}
                  </span>
                </div>
              ))}
              <div className="flex gap-2 pt-2">
                <input
                  className="flex-1 border rounded px-2 py-1 text-sm focus:outline-none focus:ring-2 focus:ring-blue-200"
                  value={input}
                  onChange={e => setInput(e.target.value)}
                  onKeyDown={e => { if (e.key === 'Enter') handleSend(); }}
                  placeholder="Type a message..."
                />
                <Button size="icon" onClick={handleSend} disabled={!input.trim()}><Send className="w-4 h-4" /></Button>
              </div>
            </CardContent>
          </Card>
        </div>
      )}
      {/* 浮动按钮 */}
      {!isOpen && (
        <Button
          onClick={() => setIsOpen(true)}
          className="h-16 w-16 rounded-full bg-gradient-to-br from-blue-400 to-purple-400 hover:from-blue-500 hover:to-purple-500 shadow-lg hover:shadow-xl transition-all duration-300 group"
          size="icon"
          style={{ cursor: 'pointer' }}
        >
          <Cat className="h-8 w-8 text-white group-hover:scale-110 transition-transform duration-200" />
        </Button>
      )}
    </div>
  );
}; 